<?php

namespace App\Service;

use App\Algorithm\ScheduleAlgorithm;
use App\Controller\Api\BaseController;
use App\Model\WorkDate;
use App\Model\WorkReservation;
use Hyperf\Di\Annotation\Inject;

class WorkService extends BaseController
{
    /**
     * @Inject()
     * @var ScheduleAlgorithm
     */
    public $scheduleAlgorithm;


    public  function scheduling($wid)
    {

        $workDateInfo = WorkDate::where(['id' => $wid])->first();

        if (is_null($workDateInfo)) {
            return null;
        }

        if ($workDateInfo['start'] < time()) {
            $workDateInfo['start'] = time();
        }


        $where[] = ['wid','=',$workDateInfo['id']];
        $where[] = ['end','>',time()];

        $occupiedTimeSlots = WorkReservation::where($where)->orderBy('start')->get()->toArray();



        $list = $this->scheduleAlgorithm->scheduling($workDateInfo['start'], $workDateInfo['end'], $occupiedTimeSlots);

        foreach ($list as $k => $v) {
            $list[$k]['type'] = 3;
            $list[$k]['status'] = 4;
            $list[$k]['wid'] = $workDateInfo['id'];
            $list[$k]['uid'] = $workDateInfo['uid'];
        }
        $list = array_merge($list, $occupiedTimeSlots);

        array_multisort(array_column($list, 'start'), SORT_ASC, $list);

        return  $list;
    }

}